import React, { PureComponent } from 'react';
import { Card, Button,Form,Radio,Row,Col,Alert,Icon,Affix,Modal,message } from 'antd';
const confirm = Modal.confirm;
import { connect } from 'dva';
import moment from 'moment';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import MsgList from '../../components/Msg/MsgList';
import MsgWeiXinDetail from '../../components/Msg/MsgWeiXinDetail';
import MsgHuDongDetail from '../../components/Msg/MsgHuDongDetail';
import MsgXunRenDetail from '../../components/Msg/MsgXunRenDetail';
import MsgXunWuDetail from '../../components/Msg/MsgXunWuDetail';
import MsgCarHelpDetail from '../../components/Msg/MsgCarHelpDetail';
import MsgXunZhaoShiZhuDetail from '../../components/Msg/MsgXunZhaoShiZhuDetail';
import MsgOtherDetail from '../../components/Msg/MsgOtherDetail';

import styles from './PlayMsg.less';
import {loading} from "../../components/NoticeIcon/index";

// 将model里面的元素 当做props的方式 传递进来
@connect(state => ({
  msg: state.msg,
}))
//将Form里面的内容以props的方式 传递进去
@Form.create()

export default class PlayMsg extends PureComponent {
  state = {
    pageNo:1,
    pageSize:10,
    selectedRowData:{},
    latestTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    radioValue:1.0,
    ids:"",

    loading: true,          //list的loading
    loadingMore: false,     //点击加载按钮的loading
    showLoadingMore: true,  //是否显示加载更多按钮判断
    data: [],

    newMsgCount:0,
    showMoreMessage:false
  }

  /**
   * 初始化渲染后触发 整个过程只调用一次，并像是第一条数据
   */
  componentDidMount() {
    this.getData((response) => {
      const data = response.data.list;
      this.setState({
        loading: false,
        data: data,
        selectedRowData: data.length > 0 ? data[0] : {},
      });
      this.getIds(data);
    });
  }

  /**
   * 页面加载完成后，每一分钟向后台发送数据，监测新消息数量
   */
  componentWillMount() {
    setInterval(()=>{
      const { dispatch } = this.props;
      const latestTime = this.state.latestTime;
      const params = {
        rsId:1,
        latestTime:latestTime,
      };
      dispatch({
        type: 'msg/getNewMsgCount',  //请求的action
        payload:params,
        callback:(response) =>{
          const newMsgCount = response.data.newMsgCount;
          this.setState({
            newMsgCount: newMsgCount,
            showMoreMessage: newMsgCount > 0 ? true:false
          });
        }
      });
      this.setState(
        () => {
          window.dispatchEvent(new Event('resize'));
        });
    },60000)
  }

  /**
   * 获取当前数据的主键ID
   * @param data
   */
  getIds = (data) => {
    var ids = "";
    for( var index = 0; index < data.length; index ++){
      ids += data[index].id;
      ids += ",";
    }
    this.setState({
      ids:ids
    });
  }

  /**
   * 加载数据方法
   */
  getData = ( loadCallBack) => {
    var self = this;
    const { dispatch } = self.props;
    const pageNo = self.state.pageNo ;
    const pageSize = self.state.pageSize ;
    const latestTime = self.state.latestTime ;
    // 需要传递的参数信息
    const params = {
      rsId:1,
      status:1,
      latestTime:latestTime,
      pageNo: pageNo,
      pageSize: pageSize,
    };
    dispatch({
      type: 'msg/listPlayMsg',  //请求的action
      payload:params,
      callback:(response) =>{
        loadCallBack(response);
        self.setState({
          showLoadingMore:response.data.pageNo == response.data.pageCount ? false:true,
        });
      }
    });
  }

  /**
   * 点击加载更多加载数据,注意这个setState是异步的
   */
  onLoadMore = () => {
    var self =this;
    const pageNo = this.state.pageNo +1;
    self.setState({
      pageNo:pageNo,
      loadingMore: true,
    } ,()=>{
      self.getData((response) => {
        const data = self.state.data.concat(response.data.list);
        self.setState({
          data:data,
          loadingMore: false,
        }, () => {
          window.dispatchEvent(new Event('resize'));
        });
        self.getIds(data);
      });
    });
  }
  /**
   * 点击展示新消息页面
   */
  showMoreNewMessage = () => {
    const self = this;
    const { dispatch } = self.props;
    const latestTime = self.state.latestTime;
    const newLatestTime = moment().format('YYYY-MM-DD HH:mm:ss');
    this.setState({
      latestTime:newLatestTime
    });
    const params = {
      rsId:1,
      status:1,
      latestTime:latestTime,
    };
    dispatch({
      type: 'msg/showMoreNewMessage',  //请求的action
      payload:params,
      callback:(response) =>{
        var newMsgData = response.data.list.concat(self.state.data);
        self.setState({
          data:newMsgData
        });
        this.getIds(newMsgData);
      }
    });
    this.setState(
      () => {
        window.dispatchEvent(new Event('resize'));
      });
  }
  /**
   * 单击事件: 显示右侧详细信息
   * @param record
   */
  handleOnClick = (record) => {
    this.setState({
      selectedRowData: record,
    });
  }

  /**
   * 更新消息状态
   */
  updateStatus = (ids,status,loadCallBack) => {
    const self = this;
    const params = {
      ids:ids,
      status:status,
      curUserId:1,
      curUserName: "审核人应该去当前登陆用户",
    };
    const { dispatch } = self.props;
    //在双击事件中，先清除前面click事件的时间处理
    dispatch({
      type: 'msg/updateMsgStatus',
      payload:params,
      callback:(response) =>{
        loadCallBack(response);
      }
    });
  }
  /**
   * 更新指定时间之前的消息状态
   */
  updateMsgStatusByTime = (customizeTime,status,loadCallBack) => {
    const self = this;
    const params = {
      customizeTime:customizeTime,
      status:status,
      rsId:1,      //登陆模块完成后，要指定为电台ID
      curUserId:1,
      curUserName: "审核人应该去当前登陆用户",
    };
    const { dispatch } = self.props;
    //在双击事件中，先清除前面click事件的时间处理
    dispatch({
      type: 'msg/updateMsgStatusByTime',
      payload:params,
      callback:(response) =>{
        loadCallBack(response);
      }
    });
  }
  /**
   * 双击事件:双击行通过
   * @param record
   */
  handleOnDoubleClick = (record,index) => {
    var self = this;
    self.updateStatus(record.id,2,(response) => {
      const resultData = this.state.data;
      resultData.splice(index,1);
      self.setState({
        data:resultData.concat([]),
      });
      this.getIds(resultData);
    });
  }
  /**
   * 点击通过按钮
   * @param record
   */
  handlePassClick = (record,index) => {
    var self = this;
    self.updateStatus(record.id,2,(response) => {
      const resultData = this.state.data;
      resultData.splice(index,1);
      self.setState({
        data:resultData.concat([]),
      });
      this.getIds(resultData);
    });
  }
  /**
   * 点击忽略按钮
   * @param record
   */
  handleIgnoreClick = (record,index) => {
    var self = this;
    self.updateStatus(record.id,4,(response) => {
      const resultData = this.state.data;
      resultData.splice(index,1);
      self.setState({
        data:resultData.concat([]),
      });
      this.getIds(resultData);
    });
  }

  /**
   * 批量通过思路：
   * 1. 页面加载的时候、点击通过忽略的时候拼接id 设置到ids中
   * 2. 处理数据为已通过
   * 3. 处理成功后回调刷新数据
   */
  handlePassCurShowClick = () => {
    var self = this;
    const ids = self.state.ids;
    confirm({
      title: '你确定要将当前显示的所有消息通过么?',
      content: '如果您点击是，当前显示的所有消息都会自动通过！',
      okText: '是',
      cancelText: '否',
      onOk() {
        self.updateStatus(ids,2,(response) => {
          self.setState({
            pageNo:1,
            loading: true,          //list的loading
            loadingMore: false,     //点击加载按钮的loading
            showLoadingMore: true,  //是否显示加载更多按钮判断
            selectedRowData:{},
            data: [],
            ids:""
          },() => {
            self.getData((response) => {
              const data = response.data.list;
              self.setState({
                loading: false,
                data: data,
                selectedRowData: data.length > 0 ? data[0] : {},
              });
              self.getIds(data);
            });
          });
        });
      },
      onCancel() {
      },
    });
  }
  /**
   * 批量忽略
   */
  handleIgnoreCurShowClick = () => {
    var self = this;
    const ids = self.state.ids;
    confirm({
      title: '你确定要将当前显示的所有消息忽略么?',
      content: '如果您点击是，当前显示的所有消息都会自动忽略！',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        self.updateStatus(ids,4,(response) => {
          self.setState({
            pageNo:1,
            loading: true,          //list的loading
            loadingMore: false,     //点击加载按钮的loading
            showLoadingMore: true,  //是否显示加载更多按钮判断
            selectedRowData:{},
            data: [],
            ids:""
          },() => {
            self.getData((response) => {
              const data = response.data.list;
              self.setState({
                loading: false,
                data: data,
                selectedRowData: data.length > 0 ? data[0] : {},
              });
              self.getIds(data);
            });
          });
        });
      },
      onCancel() {
      },
    });
  }

  /**
   * 批量忽略指定时间之前的消息
   */
  handleIgnoreCustomizeTimeClick = (miniteCount) => {
    var self = this;
    const customizeTime =  moment().subtract(miniteCount, 'minute').format('YYYY-MM-DD HH:mm:ss');
    const confirmTitle = miniteCount == 10 ? '你确定要忽略十分钟之前的消息么?' : '你确定要忽略二十分钟之前的消息么?' ;
    const confirmContent = miniteCount == 10 ? '如果您点击是，二十分钟之前的所有消息都会自动忽略！' : '如果您点击是，二十分钟之前的所有消息都会自动忽略！' ;
    confirm({
      title: confirmTitle,
      content: confirmContent,
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        self.updateMsgStatusByTime(customizeTime,4,(response) => {
          self.setState({
            pageNo:1,
            loading: true,          //list的loading
            loadingMore: false,     //点击加载按钮的loading
            showLoadingMore: true,  //是否显示加载更多按钮判断
            selectedRowData:{},
            data: [],
            ids:"",
            latestTime:moment().format('YYYY-MM-DD HH:mm:ss'),
            newMsgCount:0,
            showMoreMessage:false
          },() => {
            self.getData((response) => {
              const data = response.data.list;
              self.setState({
                loading: false,
                data: data,
                selectedRowData: data.length > 0 ? data[0] : {},
              });
              self.getIds(data);
            });
          });
        });
      },
      onCancel() {
      },
    });
  }

  /**
   * 修改 语音的播放速度
   * @param e
   */
  handleRadioValueChange= (e) => {
    this.setState({
      radioValue: e.target.value,
    });
  }

  /**
   * 一键推送 求助消息
   * @param helpId
   */
  handlePushMsgHelp = (helpId) => {
    var self = this;
    const { dispatch } = self.props;
    // 需要传递的参数信息
    const params = {
      helpId: helpId,
      pushStatus: 1,
    };
    dispatch({
      type: 'msg/updateSeekHelpInfoPushStatus',  //请求的action
      payload:params,
      callback:(response) =>{
        if(response.errorCode == 1){
          message.success('推送成功');
        }
      }
    });
  }

  /**
   * 回复消息
   * @param helpId
   * @param replayMessageValue
   */
  handleReplayMessage = (helpId,userId,replayMessageValue) => {
    var self = this;
    const { dispatch } = self.props;
    // 需要传递的参数信息
    const params = {
      msgAttachmentAddr:replayMessageValue,
      msgDirect: 1,
      userId:userId,
      rsId:1,  //用户登陆后，从后台获取
      messageFrom:2,
      helpId:helpId
    };
    dispatch({
      type: 'msg/replyMsg',  //请求的action
      payload:params,
      callback:(response) =>{
        if(response.errorCode == 1){
          message.success('推送成功');
        }
      }
    });
  }

  handleShowMsgDetail= (selectedRowData) => {
    var self = this;
    if(JSON.stringify(selectedRowData) == '{}'){
      return "";
    }else {
      var messageFrom = selectedRowData.messageFrom;
      var msgType = selectedRowData.msgType;
      if(messageFrom == '0'){
        return (
          <MsgWeiXinDetail
            selectedRowData={selectedRowData}
          />
        );
      }else {
        if(msgType == '0'){
          return (
            <MsgHuDongDetail
              selectedRowData={selectedRowData}
              handleReplayMessage={(helpId,userId,replayMessageValue) => self.handleReplayMessage(helpId,userId,replayMessageValue)}
            />
          )
        }else if(msgType == '1'){
          return (
            <MsgXunRenDetail
              selectedRowData={selectedRowData}
              handleReplayMessage={(helpId,userId,replayMessageValue) => self.handleReplayMessage(helpId,userId,replayMessageValue)}
              handlePushMsgHelp={(helpId) => self.handlePushMsgHelp(helpId)}
            />
          )
        }else if(msgType == '2'){
          return (
            <MsgXunWuDetail
              selectedRowData={selectedRowData}
              handleReplayMessage={(helpId,userId,replayMessageValue) => self.handleReplayMessage(helpId,userId,replayMessageValue)}
              handlePushMsgHelp={(helpId) => self.handlePushMsgHelp(helpId)}
            />
          )
        }else if(msgType == '3'){
          return (
            <MsgCarHelpDetail
              selectedRowData={selectedRowData}
              handleReplayMessage={(helpId,userId,replayMessageValue) => self.handleReplayMessage(helpId,userId,replayMessageValue)}
              handlePushMsgHelp={(helpId) => self.handlePushMsgHelp(helpId)}
            />
          )
        }else if(msgType == '4'){
          return (
            <MsgXunZhaoShiZhuDetail
              selectedRowData={selectedRowData}
              handleReplayMessage={(helpId,userId,replayMessageValue) => self.handleReplayMessage(helpId,userId,replayMessageValue)}
              handlePushMsgHelp={(helpId) => self.handlePushMsgHelp(helpId)}
            />
          )
        }else if(msgType == '5'){
          return (
            <MsgOtherDetail
              selectedRowData={selectedRowData}
              handlePushMsgHelp={(helpId) => self.handlePushMsgHelp(helpId)}
              handleReplayMessage={(helpId,replayMessageValue) => self.handleReplayMessage(helpId,replayMessageValue)}
            />
          );
        }
      }
    }
  }

  render() {
    const {selectedRowData,radioValue,loading,loadingMore,showLoadingMore,data,showMoreMessage,newMsgCount } = this.state;
    const moreMessageAlert = (
      <Alert
        message={(
          <div align="center">
            <Icon type="bell" spin={true} style={{ fontSize: 16, color: '#08c' }} />
            <a onClick={ () => this.showMoreNewMessage() }>有{newMsgCount}条新消息，点击加载</a>
          </div>
        )}
        type="info"
        closable
      />
    );
    return (
      <PageHeaderLayout >
        <Card bordered={false}>
          <div className={styles.playMsgList}>
            <div className={styles.tableListOperator}>
              {/*<Button type="primary" onClick={() => this.handlePassCurShowClick()}>
                批量通过当页数据
              </Button>*/}
              <Button type="primary" onClick={() => this.handleIgnoreCurShowClick()}>
                一键忽略
              </Button>
              <Button type="primary" onClick={() => this.handleIgnoreCustomizeTimeClick(10)} >
                忽略十分钟前数据
              </Button>
              <Button type="primary" onClick={() => this.handleIgnoreCustomizeTimeClick(20)}>
                忽略二十分钟前数据
              </Button>
            </div>
            <div className={styles.messageList}>
              <Affix offsetTop={0} id="affixMessageAlert" onChange={() => { document.getElementById("affixMessageAlert").children[0].style.backgroundColor = "#ffffff" ; }} >
                <div style={{backgroundColor:"#ffffff"}}>
                  <div className={styles.tableAlert} >
                    { showMoreMessage == true ? moreMessageAlert : "" }
                  </div>
                  <div style={{marginTop:8,marginBottom:8}}>
                    语音播放速度：
                    <Radio.Group onChange={this.handleRadioValueChange} value={radioValue}>
                      <Radio.Button value={1.5}>1.5倍</Radio.Button>
                      <Radio.Button value={2.0}>2.0倍</Radio.Button>
                      <Radio.Button value={2.5}>2.5倍</Radio.Button>
                      <Radio.Button value={1.0}>原速度</Radio.Button>
                    </Radio.Group>
                  </div>
                </div>
              </Affix>
              <Row gutter={24} >
                <Col xl={14} lg={24} md={24} sm={24} xs={24}>
                  <MsgList
                    className="demo-loadmore-list"
                    itemLayout="horizontal"
                    loading={loading}
                    loadingMore={loadingMore}
                    showLoadingMore={showLoadingMore}
                    data={data}
                    onLoadMore = {() => this.onLoadMore() }
                    handleOnClick= {(record) => this.handleOnClick(record) }
                    handleOnDoubleClick= {(record,index) => this.handleOnDoubleClick(record,index) }
                    handlePassClick= {(record,index) => this.handlePassClick(record,index) }
                    handleIgnoreClick= {(record,index) => this.handleIgnoreClick(record,index) }
                    userType = {2}
                    radioValue = {radioValue}
                  />
                </Col>
                <Col xl={10} lg={24} md={24} sm={24} xs={24} >
                  <Affix offsetTop={45} >
                    {this.handleShowMsgDetail(selectedRowData)}
                  </Affix>
                </Col>
              </Row>
            </div>
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
